package business

import (
	"context"
	"group-buy/group_buy/internal/models"

	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListBusinessLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListBusinessLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListBusinessLogic {
	return &ListBusinessLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListBusinessLogic) ListBusiness(req *types.ListBusinessReq) (resp *types.ListBusinessRsp, err error) {
	data := make([]*models.Business, 0)
	sql := l.svcCtx.Engine.Where("")
	if req.DealerId > 0 {
		sql = sql.And("dealer_id=?", req.DealerId)
	}
	count, err := sql.OrderBy("sort").Limit(req.Size, (req.Page-1)*req.Size).FindAndCount(&data)
	if err != nil {
		return nil, err
	}
	list := make([]*types.Business, len(data), len(data))
	for i, _ := range data {
		list[i] = &types.Business{
			Id:            data[i].Id,
			Name:          data[i].Name,
			ContactsName:  data[i].ContactsName,
			ContactsPhone: data[i].ContactsPhone,
			Address:       data[i].Address,
			WorkTime:      data[i].WorkTime,
			Preferential:  data[i].Preferential,
			Img:           data[i].Img,
			Sort:          data[i].Sort,
			DealerId:      data[i].DealerId,
			UserId:        data[i].UserId,
		}
	}

	return &types.ListBusinessRsp{
		List:  list,
		Count: count,
	}, nil
}
